package com.ruoyi.handler;

import java.nio.ByteBuffer;

import org.apache.commons.codec.binary.Hex;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.stereotype.Service;

import com.google.common.primitives.Floats;
import com.google.common.primitives.Ints;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.AttributeKey;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class Tcp9001Handler extends SimpleChannelInboundHandler<ByteBuf> {


    AttributeKey<String> productKey = AttributeKey.valueOf("productKey");

    AttributeKey<String> channelKey = AttributeKey.valueOf("channelKey");

    AttributeKey<String> deviceKey = AttributeKey.valueOf("deviceKey");

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        byte[] data = new byte[msg.readableBytes()];
		msg.readBytes(data);
        log.info("收到客户端消息：{}" , Hex.encodeHexString(data));

        byte[] wendu_byte = new byte[4];
        byte[] shidu_byte = new byte[4];
        System.arraycopy(data, 0, wendu_byte, 0, wendu_byte.length);
        System.arraycopy(data, 4, shidu_byte, 0, shidu_byte.length);
        // 温度  Ints.fromByteArray(byteArray);
        float wendu = ByteBuffer.wrap(wendu_byte).getFloat();
        // 湿度 Floats.fromByteArray(byteArray);
        float shidu =ByteBuffer.wrap(shidu_byte).getFloat();
        
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        super.userEventTriggered(ctx, evt);
        // 设备掉线事件，心跳检测超时，或者网络断开都会触发这个事件
        log.info("触发事件:{}", evt);
    }
    

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        log.info("客户端断开连接:{}", ctx.channel().remoteAddress());
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        log.info("客户端连接成功:{}", ctx.channel().remoteAddress());
    }


}
